//
//  CommentViewController.m
//  Project_2_weibo
//
//  Created by 林林 on 16/6/23.
//  Copyright © 2016年 lhn. All rights reserved.
//

#import "CommentViewController.h"
#import "AppDelegate.h"
#import "Comments.h"
#import "CommentCell.h"

@interface CommentViewController () <SinaWeiboRequestDelegate, UITableViewDelegate, UITableViewDataSource>
{
    UITableView *_commentList;
    NSMutableArray *_commentArr;
}

@end

@implementation CommentViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self requestWeiboData];
    
    [self createTableView];
}

//发起微博请求
- (void)requestWeiboData {
    
    //获取当前微博对象
    SinaWeibo *weibo = kWeiboObject;
    
    //判断微博是否已经登录
    if ([weibo isAuthValid]) {
        
        NSString *id = self.weibo.idstr;
        NSMutableDictionary *params = [@{@"id" : id} mutableCopy];
        //发起请求
        [weibo requestWithURL:@"comments/show.json"
                       params:params
                   httpMethod:@"GET"
                     delegate:self];
    }else {
        //进行登录
        [weibo logIn];
    }
    
}

//创建tableView
- (void)createTableView {
    
    _commentList = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
    _commentList.backgroundColor = [UIColor clearColor];
    _commentList.delegate = self;
    _commentList.dataSource = self;
    
    //注册cell
    UINib *nib = [UINib nibWithNibName:@"CommentCell" bundle:[NSBundle mainBundle]];
    [_commentList registerNib:nib forCellReuseIdentifier:@"CommentCell"];
    
    [self.view addSubview:_commentList];
    
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _commentArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CommentCell"];
    
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 70;
}

#pragma mark - SinaWeiboRequestDelegate

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    
    NSArray *comments = result[@"comments"];
    NSMutableArray *mArr = [[NSMutableArray alloc] init];
    for (NSDictionary *dic in comments) {
        
        Comments *comment = [Comments yy_modelWithJSON:dic];
        [mArr addObject:comment];
    }
    
    _commentArr = [mArr mutableCopy];
    
    [_commentList reloadData];
    
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
